﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using Extensions;
using System.IO;

namespace EnergyAggregator
{
    public class PlotWatt
    {
        public string UserName { get; set; }
        public string Password { get; set; }

        public string BaseURL { get; set; }

        public bool Enable { get; set; }

        public PlotWatt()
        {
            BaseURL = "http://plotwatt.com/api/v2/";
            Enable = false;
        }

        public List<string> GetMeterList()
        {
            return ListMeters().ToList();
        }

        public string[] ListMeters()
        {
            // used to build entire input
            StringBuilder sb = new StringBuilder();

            // used on each read operation
            byte[] buf = new byte[8192];

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(BaseURL + "list_meters");

            request.AddAuthorizationHeader(UserName, Password);

            // execute the request
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            // we will read data via the response stream
            Stream resStream = response.GetResponseStream();
            string tempString = null;
            int count = 0;

            do
            {
                // fill the buffer with data
                count = resStream.Read(buf, 0, buf.Length);

                // make sure we read some data
                if (count != 0)
                {
                    // translate from bytes to ASCII text
                    tempString = Encoding.ASCII.GetString(buf, 0, count);

                    // continue building the string
                    sb.Append(tempString);
                }
            }
            while (count > 0); // any more data to read?

            tempString = Regex.Replace(tempString, @"[\[\]]", "", RegexOptions.IgnoreCase);

            string[] meterList = tempString.Split(',');

            return meterList;
        }

        public void DeleteMeter(string meter)
        {
            // Create a request using a URL that can receive a post. 
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(BaseURL + "delete_meter");

            // Set the Method property of the request to POST.
            request.AddAuthorizationHeader(UserName, Password);

            request.Method = "POST";
            string postData = "meter_id=" + meter;
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            request.ContentType = "application/x-www-form-urlencoded";
            // Set the ContentLength property of the WebRequest.
            request.ContentLength = byteArray.Length;

            using (Stream dataStream = request.GetRequestStream())
            {
                dataStream.Write(byteArray, 0, byteArray.Length);

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {

                    // now we should have a response so check what the status of this is
                    switch (response.StatusCode)
                    {
                        case HttpStatusCode.OK:
                            // Display the status.
                            Console.WriteLine(response.StatusDescription);
                            // Get the stream containing content returned by the server.
                            using (Stream responseDataStream = response.GetResponseStream())
                            {
                                // Open the stream using a StreamReader for easy access.
                                string responseFromServer;

                                using (StreamReader reader = new StreamReader(responseDataStream))
                                {
                                    responseFromServer = reader.ReadToEnd();
                                }
                            }
                            break;

                        default:
                            break;
                    }
                }
            }
        }
        public void AddMeterReadings(List<MeterReading> readings)
        {
            // Create a request using a URL that can receive a post. 
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(BaseURL + "push_readings");

            // Set the Method property of the request to POST.
            request.AddAuthorizationHeader(UserName, Password);

            request.Method = "POST";

            string postData = "";
            foreach (MeterReading reading in readings)
            {
                if (!string.IsNullOrWhiteSpace(postData))
                {
                    postData += ",";
                }
                postData += string.Format("{0},{1},{2}", reading.Meter, (double)reading.Power / 1000, reading.Time);
            }

            // if we are not enabled then we will return here and not post to the site
            if (!Enable)
            {
                return;
            }

            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            request.ContentType = "application/x-www-form-urlencoded";
            // Set the ContentLength property of the WebRequest.
            request.ContentLength = byteArray.Length;
            using (Stream dataStream = request.GetRequestStream())
            {
                dataStream.Write(byteArray, 0, byteArray.Length);

                try
                {
                    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                    {

                        // now we should have a response so check what the status of this is
                        switch (response.StatusCode)
                        {
                            case HttpStatusCode.OK:
                                // Display the status.
                                Console.WriteLine(response.StatusDescription);
                                // Get the stream containing content returned by the server.
                                using (Stream responseDataStream = response.GetResponseStream())
                                {
                                    // Open the stream using a StreamReader for easy access.
                                    string responseFromServer;

                                    using (StreamReader reader = new StreamReader(responseDataStream))
                                    {
                                        responseFromServer = reader.ReadToEnd();
                                    }
                                }
                                break;

                            default:
                                break;
                        }
                    }
                }
                catch
                {
                }
            }

        }

        public void AddMeter()
        {
            // Create a request using a URL that can receive a post. 
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(BaseURL + "new_meters");

            // Set the Method property of the request to POST.
            request.AddAuthorizationHeader(UserName, Password);

            request.Method = "POST";
            string postData = "number_of_new_meters=1";
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            request.ContentType = "application/x-www-form-urlencoded";
            // Set the ContentLength property of the WebRequest.
            request.ContentLength = byteArray.Length;

            using (Stream dataStream = request.GetRequestStream())
            {
                dataStream.Write(byteArray, 0, byteArray.Length);

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {

                    // now we should have a response so check what the status of this is
                    switch (response.StatusCode)
                    {
                        case HttpStatusCode.OK:
                            // Display the status.
                            Console.WriteLine(response.StatusDescription);
                            // Get the stream containing content returned by the server.
                            using (Stream responseDataStream = response.GetResponseStream())
                            {
                                // Open the stream using a StreamReader for easy access.
                                string responseFromServer;

                                using (StreamReader reader = new StreamReader(responseDataStream))
                                {
                                    responseFromServer = reader.ReadToEnd();
                                }
                            }
                            break;

                        default:
                            break;
                    }
                }
            }
        }
    }
}
